package com.yuzhi.common.jackson;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.yuzhi.common.annotation.EnumFormat;
import io.vavr.control.Option;
import lombok.AllArgsConstructor;

import java.lang.reflect.Method;

/**
 * @ClassName EnumTranCodeSerializer
 * @Author sunshine
 * @Date 2024-04-19 11:26:54
 * @Description TODO
 */
@AllArgsConstructor
public class EnumTranCodeSerializer extends JsonSerializer<Object> {
    private static final String PACKAGE_PRE = "com.yuzhi.common.enums.";
    private EnumFormat enumFormat;

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) {
        try {
            if (ObjectUtil.isNull(value)) {
                gen.writeObject(value);
                return;
            }
            String enumClassName = PACKAGE_PRE.concat(Option.when(CharSequenceUtil.isNotBlank(enumFormat.key()), enumFormat.key()).getOrElse(gen.getOutputContext().getCurrentName()));
            String enumValueName = String.valueOf(value);
            if (StrUtil.isBlank(enumValueName)) {
                gen.writeObject(value);
                return;
            }
            // 字段名称
            String fieldName = gen.getOutputContext().getCurrentName();
            // 获取枚举类的Class对象
            Class<?> enumClass = Class.forName(enumClassName);
            if (CharSequenceUtil.isNotBlank(enumFormat.methodName())) {
                // 获取枚举类的getDescByCode方法
                Method valueOfMethod = enumClass.getMethod("getDescByCode", String.class);
                // 调用valueOf方法获取枚举对象
                Object enumValue = valueOfMethod.invoke(null, enumValueName);
                gen.writeObject(value);
                gen.writeFieldName(fieldName.concat("Desc"));
                gen.writeString((String) enumValue);
            } else {
                // 获取枚举类的valueOf方法
                Method valueOfMethod = enumClass.getMethod("valueOf", String.class);
                // 调用valueOf方法获取枚举对象
                Object enumValue = valueOfMethod.invoke(null, enumValueName);
                // 获取枚举属性值
                Method method = enumClass.getMethod("getDesc");
                gen.writeObject(value);
                gen.writeFieldName(fieldName.concat("Desc"));
                gen.writeString((String) method.invoke(enumValue));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

